package utility;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class XMLConfigurator {
	private Document 		document;
	private Element 		root;
	private XMLOutputter 	out;
	
	public void createDocument(String rootName)
	{
		this.root = new Element(rootName);
		this.document = new Document(root);
	}
	
	public void setRootAttribute(String name, String value)
	{
		root.setAttribute(name, value);
	}
	
	public void setRootText(String text)
	{
		root.setText(text);
	}
	
	public void setAttribute(Element element, String name, String value)
	{
		element.setAttribute(name, value);
	}
	
	public void setText(Element element, String text)
	{
		element.setText(text);
	}
	
	public void addRootChild(Element child)
	{
		root.addContent(child);
	}
	
	public void addChild(Element parent, Element child)
	{
		parent.addContent(child);
	}
	
	public void writeXML(String filePath) throws FileNotFoundException, IOException
	{
		out = new XMLOutputter();
		out.setFormat(Format.getPrettyFormat());
		out.output(document, new FileOutputStream(filePath));	
	}
	
	public String getRootText()
	{
		return root.getText();
	}
	
	public String getText(Element element)
	{
		return element.getText();
	}
	
	public String getAttribute(Element element, String name)
	{
		return element.getAttributeValue(name);
	}
	
	public Element getRoot()
	{
		return root;
	}
	
	public Element getElement(String name)
	{
		return root.getChild(name);
	}
	
	public void openXML(String filePath) throws JDOMException, IOException
	{
		SAXBuilder builder = new SAXBuilder();
		document = builder.build(new File(filePath));
		root = document.getRootElement();
	}
	
	@SuppressWarnings("unchecked")
	public Element findChild(String attrName)
	{
		System.out.println("FINDCHILD " + attrName);
		Element e = null;
		List<Element> elements = this.root.getChildren();
		Iterator<Element> i = elements.iterator();
		while (i.hasNext())
		{
			e = (Element) i.next();
			if(e.getName().equals("PLAYER") 
			   && 
			   e.getAttributeValue("name").equalsIgnoreCase(attrName))
				return e;
		}
		System.out.println("NOTHING FOUND!!!");
		e=null;
		return e;
	}
	
	public int getChildrenNumber()
	{
		return root.getChildren().size();
	}
}